package com.project.running.Utils;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/10/10-10-10-15:29
 * @Description：com.project.running.Utils
 */

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 纯文本格式：
 * https://www.36ip.cn/?ip=IP地址
 * JSON格式返回：
 * https://www.36ip.cn/?type=json&ip=IP地址
 * JSON格式返回
 * https：//www.36ip.cn/?type=jsonp&cb=回调函数名&ip=IP地址
 */
public class IPUtils {
    //获取Ip地址
    public static String getIpAddr(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)){
            ip = request.getHeader(" Proxy-Client-IP ");
        }
        if(ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)){
            ip = request.getHeader(" WL-Proxy-Client-IP ");
        }
        if(ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    //根据ip获取物理地址
    public static String getRealAdd(String ip){
        if("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){
            return "杰普科技有限公司";
        }
        BufferedReader br = null;
        String result = "";
        try{
            URL url = new URL("https://www.36ip.cn/?ip=" + ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while((line = br.readLine()) != null){
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
